import { ajax } from './ajax'
import ad from '@service.ad'

const unify = data => {
  const obj = {
    srcUrls: data.adList[0].imgUrlList,
    content: data.adList[0].desc,
    ...data.adList[0]
  }
  return obj
}

export default function(params, info, ua) {
  return new Promise((resolve, reject) => {
    if (params.adUnitId) {
      const isProvid = ad.getProvider()
      if (!isProvid || !ad.createNativeAd) {
        reject('not provide')
        return
      }
      let adService = ad.createNativeAd({ adUnitId: params.adUnitId })
      adService.onLoad(result => {
        resolve(unify(result))
      })
      adService.onError(e => {
        reject(e)
      })
      resolve()
    } else if (params.pid) {
      ajax
        .get(params, info, ua)
        .then(response => {
          resolve(response)
        })
        .catch(e => {
          console.error(e)
          reject(e)
        })
    }
  })
}
